﻿using AntdUI;
using BST250301TestStand.Models;
using BST250301TestStand.Models.Helpers;
using BST250301TestStand.Models.Utils;
using CsvHelper;
using MathNet.Numerics.Distributions;
using Mysqlx.Crud;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel; // 用于 .xlsx 文件
using Org.BouncyCastle.Asn1;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static Azure.Core.HttpHeader;
using static System.ComponentModel.Design.ObjectSelectorEditor;

namespace BST250301.Views
{
    public partial class Report : UserControl
    {
        private AntdUI.Window window;
        AntList<RecordData> antList = new AntList<RecordData>();
        private string PlanName;
        private string SubPlanName;
        private string ProjectName;
        private string SNName;
        public Report()
        {
            InitializeComponent();
            InitData();
            InitTableColumns();
            BindEventHandler();
        }

        private void BindEventHandler()
        {
            btnRefrence.Click += async (sender, e) => await btnRefrence_Click();
        }

        private void InitData()
        {
            datePicker1.Value = DateTime.Now.AddDays(-1);
            datePicker2.Value = DateTime.Now;

            this.selectProject.Items.Clear();
            var list = DB.GetProjectNameList();
            if (list.Count > 0)
            {
                foreach (var item in list)
                {
                    this.selectProject.Items.Add(item.Name);
                }
            }
            this.selectSubPlan.Items.Clear();
            var plateList = DB.GetTestTemplate(MainWindow.configapp.PlanName);
            if (plateList.Count > 0)
            {
                foreach (var item in plateList)
                {
                    selectSubPlan.Items.Add(item.TestName);
                }
            }
        }
        private void InitTableColumns()
        {
            table_base.Columns = new ColumnCollection() {
                new AntdUI.Column("ID", "记录ID",ColumnAlign.Center){ Width ="50"},
                new AntdUI.Column("ProjectDT","测试时间"),
                new AntdUI.Column("PlanName","方案名称"),
                new AntdUI.Column("SubPlanName","项目模板"),
                new AntdUI.Column("ProjectName","测试项目"),
                new AntdUI.Column("ProductSN","产品SN"),
                new AntdUI.Column("Times","测试次第"),
                new AntdUI.Column("Name","数据名"),
                new AntdUI.Column("DefaultValue","标准值"),
                new AntdUI.Column("ReadValue","取值"),
                new AntdUI.Column("ReadAVG","取值均值"),
                new AntdUI.Column("ReadMax","取值最大值"),
                new AntdUI.Column("ReadMin","取值最小值"),
                new AntdUI.Column("QC","评判"),
                new AntdUI.Column("Note","备注"),
            };
            table_base.Bordered = true;
        }

        public void SetSN(string sn)
        {
            this.inputSN.Text = sn;
        }
        private async Task btnRefrence_Click()
        {
            DateTime dtstart = datePicker1.Value.Value.Date;
            DateTime dtsend = datePicker2.Value.Value.Date.AddDays(1);
            antList = await GetReport(selectPlan.Text.Trim(), selectSubPlan.Text.Trim(), selectProject.Text.Trim(), inputSN.Text.Trim(), dtstart, dtsend);
            if (antList != null)
            {
                table_base.Binding(antList);
                table_base.Bordered = true;
            }
        }

        private static string GetNVHDataFileName(string sn, DateTime dt)
        {
            string directoryPath = MainWindow.configapp.NVHPath;
            string searchPattern = $"*{sn}_{dt.ToString("yyyyMMdd")}*"; // 包含"keyword"的文件20251101142842_NG
            try
            {
                string[] files = Directory.GetFiles(directoryPath, searchPattern);
                if (files.Length == 0)
                {
                    int ws = 60;
                    while (ws > 0)
                    {
                        ws--;
                        Thread.Sleep(500);
                        files = Directory.GetFiles(directoryPath, searchPattern);
                        if (files.Length > 0)
                            return Path.GetFullPath(files.Last());
                    }
                }
                else
                {
                    return Path.GetFullPath(files.Last());
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }
        private void Table_base_CellClick(object sender, TableClickEventArgs e)
        {

        }

        private async Task<AntList<RecordData>> GetReport(string plan, string subplan, string projectname, string sn, DateTime? dtstart, DateTime? dtend)
        {
            PlanName = plan;
            SubPlanName = subplan;
            ProjectName = projectname;
            SNName = sn;
            return DB.GetResultParameters(plan, subplan, projectname, sn, dtstart, dtend);

        }

        private void buttonExploe_Click(object sender, EventArgs e)
        {
            try
            {
                var listReport = new AntdUI.AntList<RecordReport>();

                // antList =SELECT * FROM resultparameter WHEREID
                // PlanID \PlanName\ SubPlanID\SubPlanName\ProjectID \ ProjectName\ ProductSN \ ProjectDT \Name\DataType\Desc\QC \DefaultValue\ReadValue \ReadAVG \ReadMax\ReadMin\Unit
                foreach (var item in antList)
                {
                    var reprot = DB.GetProjectListRecordReport(item.ProjectID);
                    //SELECT * FROM testprojects WHERE Code = '{code}'  order by Code;ID\ProjectName \Desc\TestDuration\ProjectCode\OilSet\DriverSpeed \CFStatusSet\CRStatusSet\CPTOStatusSet\GearM\GearS \GearPTO 
                    if (reprot != null)
                    {
                        reprot.ID = item.ID;
                        reprot.PlanName = item.PlanName;
                        reprot.TemplateName = item.SubPlanName;
                        reprot.ProjectName = item.ProjectName;
                        reprot.DT = item.ProjectDT;
                        reprot.SN = item.ProductSN;
                        reprot.Times = item.ProductTimes;
                        reprot.ReadReportName = item.Name;
                        reprot.ReadAVG = item.ReadAVG;
                        reprot.ReadValue = item.ReadValue;
                        reprot.DefaultValue = item.DefaultValue;
                        reprot.StandardMax = item.StandardMax;
                        reprot.StandardMin = item.StandardMin;
                        reprot.ReadMax = item.ReadMax;
                        reprot.ReadMin = item.ReadMin;
                        reprot.ReadSum = item.ReadSum;
                        reprot.ReadCount = item.ReadCount;
                        reprot.QC = item.QC;
                        reprot.Unit = item.Unit;
                        listReport.Add(reprot);
                    }
                }

                string file = $"D:\\Report\\Plan_{PlanName}_Template_{SubPlanName}_Project_{ProjectName}_SN_{SNName}_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv";

                //CSVH.SaveListToCsvByName<RecordData>(antList.ToList(), file);
                //CPTO接合	40±5℃	CPTO	主N副N	1200		次数（次）	变速箱油温	有无震动、异响	-	共测10次

                var writer = new StreamWriter(file);
                var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
                csv.WriteRecords(listReport.Select(x => new { 记录ID = x.ID, 方案 = x.PlanName, 项目模板 = x.TemplateName, 项目名称 = x.ProjectName, 产品SN = x.SN, 测试次第 = x.Times, 记录时间 = x.DT.ToString("yyyy-MM-dd HH:mm:ss"), 设定油温 = x.OilSet, CF状态 = x.CFStatusSet, CR状态 = x.CRStatusSet, PTO状态 = x.CPTOStatusSet, 主档 = x.GearM, 副档 = x.GearS, PTO档 = x.GearPTO, 转速 = x.DriverSpeed, 测试参数 = x.ReadReportName, 参数标准值 = x.DefaultValue, 标准值Max = x.StandardMax, 标准值Min = x.StandardMin, 取值 = x.ReadValue, 取值平均 = x.ReadAVG, 取值最大 = x.ReadMax, 取值最小值 = x.ReadMin, 单位 = x.Unit, 评定结果 = x.QC }));
                writer.Close();
                if (File.Exists(file))
                {
                    Process.Start(new ProcessStartInfo(file) { UseShellExecute = true });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"错误：{ex.Message}");
            }
        }
    }
}
